package edu.pku.sei.mte.mtemodel.model;

import java.util.ArrayList;
import java.util.List;

import edu.pku.sei.mte.mtemodel.core.DataType;
import edu.pku.sei.mte.mtemodel.graph.GraphEdge;
import edu.pku.sei.mte.mtemodel.metamodel.RAttribute;
import edu.pku.sei.mte.mtemodel.metamodel.RTypeReference;
import edu.pku.sei.mte.utilities.Visitor;

public class MReference extends GraphEdge<MClass,MModelGraph> implements MModelObject {

	private RTypeReference type;
	private List<MAttribute> attributes;
	public MModelGraph getModelGraph() {
		return (MModelGraph)super.getHost();
	}

	
	public RTypeReference getType() {
		return type;
	}

	public void setType(DataType type) {
		this.type = (RTypeReference)type;
	}

	public MAttribute getAttribute(String name) {
		List<MAttribute> l = getAttributes();
		for(MAttribute a : l) {
			if(name.equals(a.getName()))
				return a;
		}
		RTypeReference type = getType();
		if(type!=null){
			RAttribute ra = type.getAttribute(name);
			
			if(ra!=null){
				MAttribute att = new MAttribute();
				att.setName(name);
				att.setType(ra.getType());
				att.setValue(ra.getDefaultValue());
				
				l.add(att);
				att.setHost(this);
				
				return att;
			}
		}
		
		return null;
	}

	public List<MAttribute> getAttributes() {
		if(this.attributes==null)
			this.attributes = new ArrayList<MAttribute>();
		return this.attributes;
		//return null;
	}
	
	public MClass getEnd(MClass from, String name){
		RTypeReference rt = this.getType();
		if(this.getTarget()==from){
			if(name.equals(rt.getSourceRole()))
				return (MClass) this.getSource();
		}
		if(this.getSource()==from){
			if(name.equals(rt.getTargetRole()))
				return (MClass) this.getTarget();
		}
		return null;
	}

	@Override
	public Object accept(Visitor visitor) {
		return visitor.visitMReference(this);
	}
	
}
